import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
(function (window, document, $) {
    let _vm, savetype, entriesmater, getEntryInfo = [], nextEntryId = 1, operaEntryId, saveEntry, checkSale, fassistUnitVal;
    let _areaList = [], _areaId = {}, _specLevelArry = [], _province = [], _mType = [], _district = [], _street = [];
    let checkboxList = [], employeesList = [], checkEmploy = [], allPigNumcode = [];
    const BaseCfgUrl = Utils.CurDomain.BaseCfgUrl;
    const _json = Utils.ParsingUrl(window.location);
    //胎次
    let parity = [
        { id: 0, name: 0 },
        { id: 1, name: 1 },
        { id: 2, name: 2 },
        { id: 3, name: 3 },
        { id: 4, name: 4 },
        { id: 5, name: 5 },
    ]
    const _page = {
        search: "",
        breedBatchId: "",
        parity: 0,
        pigStatus: [],
        search: "",
        pageSize: 50,
        pageIndex: 0,
        totalPages: -1
    };

    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    "entries": [
                        {
                            "seq": 0,
                            "farmOrgId": "",// 农场ID
                            "farmOrgName": "",// 农场名称
                            "specLevel": "",// 销售品类
                            "carNo": "",//运输车牌
                            "transferCarNo": "",//中转车牌
                            "count": 0,// 数量
                            "subMeasuerCount": 0,// 辅助计量数量
                            "weight": 0,// 重量
                            "grossWeight": 0,// 重量
                            "tareWeight": 0,// 重量
                            "materialId": "",
                            "materialName": "",// 物料名称
                            "materialNumCode": "",// 物料编码
                            "baseMeasureUnit": "",// 基础计量单位
                            "subMeasureUnit": "",// 辅助计量单位
                            "breedBatchId": "",
                            "breedBatchName": "",// 批次名称
                            "attaches": "" // 附件
                        }
                    ],
                    "breedPigEntries": [
                        {
                            "seq": 0,
                            "pigId": "",
                            "earNum": "",
                            "earTag": "",
                            "pigStatus": 0,
                            "parity": 0,
                            "line": ""
                        }
                    ],
                    attaches: [],
                    images: [],///处理weui自带上传插件回显重新上传时的问题
                    pickerData: [],
                    uploadCount: 0,
                    page: { ..._page },
                }
            },
            methods: {
                submit() {
                    //车牌
                    const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
                    //保留两位小数
                    const FLOAT_Method = /^\d+(\.\d{1,2})?$/;

                    if (!Utils.IsNotNull($(`#farmOrgId`).val())) {
                        return $.toptip(`请选择农场!`, 'warning');
                    }
                    if (!Utils.IsNotNull($(`#breedBatchId`).val())) {
                        return $.toptip(`请选择养殖批次!`, 'warning');
                    }
                    if (!Utils.IsNotNull($(`#materialid`).select2('data'))) {
                        return $.toptip(`请选择物料!`, 'warning');
                    }
                    if (allPigNumcode.includes($('#materialid').val()) && !Utils.IsNotNull(checkEmploy)) {
                        return $.toptip(`请选择种猪耳号!`, 'warning');
                    }
                    if (!Utils.IsNotNull($(`#specLevel`).select2('data'))) {
                        return $.toptip(`请选择销售品类!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#count').val())) {
                        return $.toptip(`数量不能为空!`, 'warning');
                    }
                    if (!(/(^[1-9]\d*$)/.test(($('#count').val())))) {
                        return $.toptip(`数量必须大于0!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#weight').val())) {
                        return $.toptip(`净重不能为空!`, 'warning');
                    }
                    if (Number($('#weight').val()) == 0 || !(FLOAT_Method.test(($('#weight').val())))) {
                        return $.toptip(`净重必须大于0且小数点后最多为两位!`, 'warning');
                    }
                    if (!Utils.IsNotNull($(`#grossWeight`).val())) {
                        return $.toptip(`毛重不能为空!`, 'warning');
                    }
                    if (Number($('#grossWeight').val()) == 0 || !FLOAT_Method.test($('#grossWeight').val())) {
                        return $.toptip(`毛重必须大于0且小数点后最多为两位!`, 'warning');
                    }
                    if (!Utils.IsNotNull($(`#tareWeight`).val())) {
                        return $.toptip(`皮重不能为空!`, 'warning');
                    }
                    if (!FLOAT_Method.test($('#tareWeight').val())) {
                        return $.toptip(`皮重必须大于等于0且小数点后最多为两位!`, 'warning');
                    }
                    if (!Utils.IsNotNull($('#carNo').val())) {
                        return $.toptip(`运输车牌不能为空!`, 'warning');
                    }
                    let carNo = $(`#carNo`).val().toUpperCase();
                    if (!carNo.match(LICENSE_PLATE)) {
                        return $.toptip(`请输入正确的运输车牌!`, 'warning');
                    }
                    if (Utils.IsNotNull($(`#transferCarNo`).val())) {
                        let transferCarNo = $(`#transferCarNo`).val().toUpperCase();
                        if (!transferCarNo.match(LICENSE_PLATE)) {
                            return $.toptip(`请输入正确的中转车牌!`, 'warning');
                        }
                    }

                    let mId = $(`#materialid`).select2('data')[0].id
                    let counts = $('#count').val()
                    let isEdit = JSON.parse(getUrlKey('isEdit'))
                    let entries = {
                        "seq": isEdit ? parseInt(getUrlKey('index')) : parseInt(getUrlKey('index')) + 1,
                        "farmOrgId": $("#farmOrgId").select2('data')[0].id,// 农场ID
                        "farmOrgName": $("#farmOrgId").select2('data')[0].name, // 农场名称
                        "specLevel": $('#specLevel').val(),// 销售品类
                        "carNo": $('#carNo').val().toUpperCase(),//运输车牌
                        "transferCarNo": $('#transferCarNo').val().toUpperCase(),//中转车牌
                        "count": counts,// 数量
                        "subMeasuerCount": parseInt(Utils.toThousands($(`#materialid`).select2('data')[0].coefficient || 0 * counts, 0)),// 辅助计量数量
                        "weight": $('#weight').val(),// 重量
                        "tareWeight": Number($(`#tareWeight`).val()),
                        "grossWeight": Number($(`#grossWeight`).val()),
                        "materialId": mId,
                        "materialName": $(`#materialid`).select2('data')[0].name || $("#materialName").val(),
                        "materialNumCode": $(`#materialid`).select2('data')[0].numCode || $("#materialNumCode").val(),
                        "baseMeasureUnit": $(`#materialid`).select2('data')[0].baseMeasureUnit || $("#baseMeasureUnit").val(),
                        "subMeasureUnit": $(`#materialid`).select2('data')[0].subMeasureUnit || $("#subMeasureUnit").val(),
                        "breedBatchId": $(`#breedBatchId`).select2('data')[0].id,
                        "breedBatchName": $(`#breedBatchId`).select2('data')[0].text,
                        "attaches": "", // 附件
                    }
                    let _breedPigEntries = [];
                    $.each(checkEmploy, function (i, p) {
                        _breedPigEntries.push(
                            {
                                "seq": isEdit ? parseInt(getUrlKey('index')) : parseInt(getUrlKey('index')) + 1,
                                "pigId": p.id,
                                "earNum": p.earNum,
                                "earTag": p.earTag,
                                "pigStatus": p.pigStatus,
                                "parity": p.parity,
                                "line": p.line
                            }
                        )
                    });

                    // 返回附件ID 数组
                    let ids = _vm.images.map(item => item.imageId)
                    // 数组以,号组合
                    entries.attaches = ids.join(',')
                    let arry = {
                        entries: entries,
                        breedPigEntries: _breedPigEntries
                    }
                    savetips(arry)
                }
            }
        });

        // master()
        _select2Info();
        uploadInit();
        _initCommand();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式\
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../deliverbills/adddeliver.html?v=${Utils.GetTime()}`;
        });

        //运输车牌
        //$(`#carNo`).bind('input porpertychange', function () {
        //    $(`#carNo`).val($(`#carNo`).val().toUpperCase());
        //});
        ////中转车牌
        //$(`#transferCarNo`).bind('input porpertychange', function () {
        //    $(`#transferCarNo`).val($(`#transferCarNo`).val().toUpperCase());
        //});
        // 获取主表数据
        let deliverDatas = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        //点击耳号选择
        $(".reportLead").on('click', function () {
            if (!Utils.IsNotNull($('#breedBatchId').val()) || !Utils.IsNotNull($('#parity').val()) || !Utils.IsNotNull($('#materialid').val())) {
                $.toptip('请先选择养殖批次、物料、胎次', 'warning');
                return
            }
            if ((deliverDatas.pigType != 1 && deliverDatas.pigType != 2 && deliverDatas.pigType != 5)) {
                $.toptip('猪只类型必须是种猪或淘汰母猪或妊娠母猪', 'warning');
                return
            }

            $("#report-contact").popup();
            $("#content").empty();
            refreshQuery();
        });

        $(document).on('click', '#iscroll .weui-check__label', function (event) { // 搜索回车事件
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            if (!isChecked == true && checkboxList.includes($(this).data("id")) == false) {
                checkboxList.push($(this).data("id"));
            } else {
                checkboxList.splice(checkboxList.indexOf($(this).data("id")), 1);
            }
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length} 个`);
        });

        // 取消按钮
        $("#cancelSub").on('click', function () {
            let checkHistory = [...checkEmploy.map(item => { return item.id })] || [];// 点取消时的上一次数据
            checkboxList = checkHistory;// 上一次点 确定的数据  赋值给  选中的数据
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length} 个`);
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
        // 确定
        $("#subEmployees").on('click', function () {
            let subData = [...checkboxList.map(item => { return [...employeesList, ...checkEmploy].find(item1 => item1.id == item); })] || [];
            checkEmploy = subData;
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
    }

    //下拉框数据
    const _select2Info = async () => {
        let allPigNum = await DeliverApi.getPrmtSettings('PIGNUMCODE')
        allPigNumcode = JSON.parse(allPigNum)
        //农场
        await DeliverApi.queryDepList(getUrlKey('orgId'), 1, '210').then(res => {
            $(`#farmOrgId`).select2({
                placeholder: '请选择农场...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        //text: `${item.name}(${item.numCode})`,
                        text: item.name,
                        name: item.name
                    }
                }),
            });
            $("#farmOrgId").setSelectValue();

            $('#farmOrgId').on("select2:select", function () {
                $('#breedBatchId').prop('disabled', false);
            });
        });
        //销售品类
        await requestDict(DictionaryType.LEVEL_TYPE).then(res => {
            _specLevelArry = res.data;
            $('#specLevel').select2({
                placeholder: '请选择销售品类...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            $("#specLevel").setSelectValue();
            if (Utils.IsNotNull(_vm.entries[0].specLevel)) {
                $(`#specLevel`).setSelectValue(_vm.entries[0].specLevel);
            }

            // 养殖批次
            Select2Page($(`#breedBatchId`), `${BaseCfgUrl}/breedbatchs/rlist`, (params) => {
                return JSON.stringify({
                    farmOrgId: $(`#farmOrgId`).val(),
                    fiOrgId: '',
                    tags: '',
                    name: params.term,
                    isEnd: false,
                    pageSize: 20,
                    pageIndex: (params.page || 1) - 1
                })
            }, "POST", {
                templateResult: function (res) {
                    return `${res.name == undefined ? res.text : res.name}`;
                }
            });
            $('#breedBatchId,#parity,#materialid').on("select2:select", function () {
                checkboxList = [], employeesList = [], checkEmploy = []
                $("#choose").text(`已选择:0 个`);
            });

            if (Utils.IsNotNull(_vm.entries[0].breedBatchId)) {
                $(`#breedBatchId`).prop('disabled', false);
                $(`#breedBatchId`).setSelectValue(_vm.entries[0].breedBatchId, _vm.entries[0].breedBatchName);
            }

        });
        //获取物料信息
        // $(`#materialid`).select2({
        //     language: "zh-CN",
        //     ajax: {
        //         url: `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`,
        //         dataType: 'json',
        //         type: 'GET',
        //         headers: {
        //             Authorization: "Bearer " + Utils.GetSNAuthAT(),
        //             "Content-Type": 'application/json',
        //             Accept: 'application/json',
        //             "Access-Control-Allow-Origin": '*',
        //             "Access-Control-Allow-Headers": "X-Requested-With",
        //             "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"
        //         },
        //         data: function (params) {
        //             return {
        //                 MGroupId: DictionaryType.MATERIAL_TYPE,
        //                 SearchInfo: params.term,
        //                 PageSize: 10,
        //                 PageIndex: (params.page || 1) - 1
        //             };
        //         },
        //         processResults: function (data, params) {
        //             params.page = params.page || 1;
        //             let _data = data.data.items.map(item => {
        //                 item.text = `${item.name}(${item.numCode})`;
        //                 return item;
        //             });
        //             return {
        //                 results: _data,// 后台返回的数据集
        //                 pagination: {
        //                     more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
        //                 }
        //             };
        //         },
        //         minimumInputLength: 1,
        //     }
        // });
        let allMaterial = await DeliverApi.postMaterial()
        let allMaterialInfo = allMaterial.items.filter(item => item.numCode.substring(0, 2) == '14')
        $(`#materialid`).select2({
            placeholder: '请选择物料...', //默认文字提示
            language: "zh-CN",//汉化
            data: allMaterialInfo.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    ...item
                }
            }),
        });

        //胎次
        $(`#parity`).empty().select2({
            placeholder: `请选择胎次...`, //默认文字提示
            language: "zh-CN",//汉化
            //allowClear: true,//允许清空
            data: parity.map(item => {
                return {
                    id: item.id,
                    text: item.name
                }
            })
        });
        $(`#parity`).setSelectValue();

        $("#materialid").setSelectValue();
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seq = getUrlKey('index')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.entries.find(item => item.seq == seq);
            let pig = getEntryInfo.breedPigEntries.filter(item => item.seq == seq);
            $(`#breedBatchId`).prop('disabled', false);
            $("#farmOrgId").setSelectValue(datas.farmOrgId)
            $("#breedBatchId").setSelectValue(datas.breedBatchId, datas.breedBatchName)
            $("#materialid").setSelectValue(datas.materialId, datas.materialName)
            $("#materialName").val(datas.materialName)
            $("#materialNumCode").val(datas.materialNumCode)
            $("#baseMeasureUnit").val(datas.baseMeasureUnit)
            $("#subMeasureUnit").val(datas.subMeasureUnit)
            $("#parity").setSelectValue(pig[0]?.parity)
            $("#specLevel").setSelectValue(datas.specLevel)
            $("#count").setSelectValue(datas.count)
            $("#weight").setSelectValue(datas.weight)
            $(`#tareWeight`).val(datas.tareWeight)
            $(`#grossWeight`).val(datas.grossWeight)
            $("#carNo").setSelectValue(datas.carNo)
            $("#transferCarNo").setSelectValue(datas.transferCarNo)
            if (Utils.IsNotNull(datas.attaches)) {
                _images(datas.attaches);
            }
            $("#choose").text(`已选择:${pig.length}个`);
            $('#subEmployees').text(`确定(${pig.length})`);
            pig.map(item => {
                checkEmploy.push({
                    ...item,
                    id: item.pigId
                })
            })
            checkboxList = pig.map(item => item.pigId);
            editEmployees();
        }

        // $(`#earNum`).empty().select2({
        //     placeholder: `请选择耳号...`, //默认文字提示
        //     language: "zh-CN",//汉化
        //     //allowClear: true,//允许清空
        // });

        // if (Utils.IsNotNull($(`#breedBatchId`).val()) && Utils.IsNotNull($(`#parity`).val()) && $(`#materialid`).select2('data')[0].name == "种猪") {
        //     $(`#earNum`).prop('disabled', false)
        //     _select2EarNum($(`#breedBatchId`).val(), $(`#parity`).val(), 'earNum');
        // }
        //  计算净重
        $('#grossWeight,#tareWeight').on('change', function () {
            let grossWeight = $('#grossWeight').val()
            let tareWeight = $('#tareWeight').val()
            let netWeight = Number(grossWeight) - Number(tareWeight)
            $('#weight').val(netWeight)
        })
    }

    // 上传图片的
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(res => {
            if (res.isSucceed) {
                let _list = _vm.images;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: upFiles.url,
                    name: newName,
                });
                _vm.attaches.push(res.data);
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.images[i].id);
                    $(this).attr('data-image-id', _vm.images[i].imageId);
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-suffix', _vm.images[i].type);
                    $(this).attr('data-url', _vm.images[i].url);
                    $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                $.hideLoading();
                $.closeModal();
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }

    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                // 获取处理完的图片文字
                let file = publicFileDraw(this.name, _vm);
                // ？
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });

        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    // 保存提示
    const savetips = (data) => {
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        let getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
                        let entries = [], breedPigEntries = []
                        if (Utils.IsNotNull(getEntryInfo)) {
                            entries = getEntryInfo?.entries || []
                            breedPigEntries = getEntryInfo?.breedPigEntries || []
                        }
                        // 判断Sessions是否有数据  如果有 并且  不是修改分录
                        if (Utils.IsNotNull(entries) && isEdit == false) {
                            entries.push(data.entries)
                        }
                        else if (Utils.IsNotNull(entries) && isEdit) {
                            entries[seq == 0 ? 0 : seq - 1] = data.entries
                        } else {
                            // 如果没有 并且不是修改分录
                            entries[0] = data.entries
                        }
                        // 耳号
                        if (Utils.IsNotNull(breedPigEntries) && isEdit == false) {
                            breedPigEntries.push(...data.breedPigEntries)
                        }
                        else if (Utils.IsNotNull(breedPigEntries) && isEdit) {
                            breedPigEntries = breedPigEntries.filter(item => {
                                return item.seq != seq
                            })
                            breedPigEntries.push(...data.breedPigEntries)
                        }
                        else {
                            // 如果没有 并且不是修改分录
                            breedPigEntries.push(...data.breedPigEntries)
                        }
                        let entryInfo = { entries: entries, breedPigEntries: breedPigEntries }
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", entryInfo))
                        location.href = `./adddeliver.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    // 解决字段过长
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    let _list = _vm.images;
                    _list.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (["jpg", "jpeg", "png", 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;

                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

    //查询耳号
    const _select2EarNum = () => {
        let _data = _vm._data.page;
        let _list = [];
        DeliverApi.postPigdocs(_data).then(res => {
            let _page = {
                breedBatchId: $('#breedBatchId').val(),
                parity: $('#parity').val(),
                search: $('#searchInput').val(),
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages
            }
            _vm._data.page = Object.assign({}, _page);
            if (!Utils.IsNotNull($('#searchInput').val()) && _data.pageIndex == 0) {
                _list.push(...checkEmploy);
            }
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__bd" aria-hidden="true">
                        <div class="demo_badge_desc lab_numCode">耳号：${item.earNum}</div>
                        <div class="demo_badge_desc lab_numCode">耳刺：${item.earTag}</div>
                        <div class="demo_badge_desc lab_numCode">品系：${item.line}</div>
                        <div class="demo_badge_desc lab_numCode">胎次：${item.parity}</div>
                    </div>
                </label>`
                $("#content").append(labhtml);
            });

            checkboxList.map(item => $(`#${item}`).prop("checked", true));
            employeesList = [...employeesList, ...res.items];
        });
    }

    const editEmployees = () => {
        weui.searchBar('#searchInput');
        //TODO : 员工上拉加载
        $("#iscroll").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _select2EarNum();
                self.loading = false;
            }, 500);   //模拟延迟
        });
        search();
    }

    const refreshQuery = () => {
        let _page = {
            "search": $('#searchInput').val(), "pageIndex": 0, "totalPages": -1, "pageSize": 50, "pigStatus": [], breedBatchId: $('#breedBatchId').val(),
            parity: $('#parity').val()
        };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        _select2EarNum();
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    const search = () => {
        let $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchForm = $('#searchForm'),
            $searchCancel = $('#searchCancel');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#content").empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#content").empty();
            refreshQuery()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#content").empty();
            refreshQuery();
            $searchInput.blur();
        });
    }


})(window, document, jQuery)